package com.semanticweb.webapp.search;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import com.semanticweb.project.search.api.SearchAPI;
import com.semanticweb.project.search.api.SearchAPIImpl;
import com.semanticweb.webapp.model.ontology.Item;
import com.semanticweb.webapp.ontology.OntBundle;

public class ItemSearch {

    private static final String INDEX_DIR = OntBundle.getString("INDEX_DIR");

    private SearchAPI search;
    private File indexDir;

    public ItemSearch() {
        try {
            this.search = new SearchAPIImpl();
            this.indexDir = new File(INDEX_DIR);
        } catch (final Exception e) {
            e.printStackTrace();
        }
    }

    public void index(final Item item) {
        this.search.index(this.indexDir, item);
    }

    public List<Item> search(final String query) {
        final List<String> result = this.search.search(this.indexDir, query, SearchMD.CONTENT.getKey(), 10);
        final List<Item> items = new ArrayList<Item>();
        for (final String s : result) {
            final Item item = new Item(s);
            item.fromRDF();
            items.add(item);
        }
        return items;
    }

    public void clearIndex() {
        for (final File f : this.indexDir.listFiles()) {
            if (f.isDirectory()) {
                deleteDir(f);
            } else {
                f.delete();
            }
        }
    }

    private void deleteDir(final File dir) {
        if (dir.isDirectory()) {
            for (final File f : dir.listFiles()) {
                if (f.isDirectory()) {
                    deleteDir(f);
                } else {
                    f.delete();
                }
            }
            dir.delete();
        }
    }

    public SearchAPI getSearchAPI() {
        return this.search;
    }

    public File getIndexDir() {
        return this.indexDir;
    }
}
